<script setup name="ConMy">
import ContractList from "@/views/contract/my/contractList.vue"
import {addCon, createConNo, deleteCon, getConMyTemplatePageList} from "@/api/contract/myContract.js"
import {genFileId} from "element-plus";
import {useRoute} from "vue-router";
import {filemakerctrl} from "js-pageoffice";
import SelectTemplateList from "@/views/common/selectTemplateList.vue";
import {selectTemplateFunctions} from "@/utils/selectTemplate.js";
import {tabFunctions} from "@/utils/tab.js";

const {proxy} = getCurrentInstance()
const {conStatus, tradeType} = proxy.useDict(["tradeType", false], ["conStatus", true])
const addOpen = ref(false)
const addTitle = ref('')
const loading = ref(false)
const isDisabledButtons = ref(false)
const route = useRoute()
const activeTabName = ref(route.query?.conStatus || '')
const uploadRef = ref()
const upload = reactive({
  isUploading: false
})
const hasPeriod = ref(false)
const data = reactive({
  addForm: {
    conNo: '',
    templateId: null,
    templateName: '',
    conFile: null,
    templateListOpen: false,
    tradeType: '',
    hasPeriod: '否',
    dateRange: []
  },
  rules: {
    conNo: [{ required: true,  message: "合同编号不能为空", trigger: 'change'}, { max: 50, message: "合同编号长度不能超过 50 个字符", trigger: 'change'}],
    templateName: [{ required: true,  message: "合同文件不能为空", trigger: 'change'}],
    name: [{ required: true,  message: "合同名称不能为空", trigger: 'change' }, { max: 100, message: "合同名称长度不能超过 100 个字符", trigger: 'change'}],
    tradeCompany: [{ required: true,  message: "对方单位名称不能为空", trigger: 'change' }, { max: 255, message: "对方单位名称长度不能超过 255 个字符", trigger: 'change'}],
    tradeType: [{ required: true,  message: "请选择买卖方向", trigger: 'change'}],
    dateRange: [{required: true, message: '请选择合同固定期限的起止日期'}],
    total: [{ required: true,  message: "合同金额不能为空", trigger: 'change' }, { pattern: /^(?:[1-9]\d*(?:\.\d{1,2})?|0(?:\.\d{1,2})?)$/, message: '请输入大于等于0的有效合同金额，做多可保留两位小数', trigger: 'change' }],
    memo: [{ max: 255, message: "备注内容长度不能超过 255 个字符", trigger: 'change'}]
  }
})
const {addForm, rules} = toRefs(data)
const contractListRefs = ref([])
const templateListOpen = ref(false)
const customReadonlyInputStyle = ref({cursor: 'not-allowed'})
const {
  openTemplateDialog,
  closeTemplateDialog,
  getTemplateList
} = selectTemplateFunctions(getConMyTemplatePageList, '选择合同模板', templateListOpen)
const {
  handChangeTab,
  handClickTab,
  loopSetRef
} = tabFunctions(activeTabName, contractListRefs)

onActivated(() => {
  const conStatus = route.query.conStatus
  if (conStatus != null) {
    handChangeTab(conStatus)
  }
})

/** 重置操作表单 */
function reset() {
  addForm.value = {
    conNo: '',
    templateId: null,
    templateName: '',
    conFile: null,
    templateListOpen: false,
    tradeType: '',
    hasPeriod: '否',
    dateRange: []
  }
  proxy.resetForm("addFormRef")
}

/** 取消按钮 */
function cancel() {
  reset()
  addOpen.value = false
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  addOpen.value = true
  addTitle.value = "新建合同"
}

function generateConNo() {
  createConNo().then(conNo => {
    addForm.value.conNo = conNo
  })
}

function setBackdropOrDisableForDialog(isBackdropOrDisable) {
  upload.isUploading = isBackdropOrDisable
  loading.value = isBackdropOrDisable
  isDisabledButtons.value = isBackdropOrDisable
}

function wordAutoFill(conId) {
  filemakerctrl.SaveFilePage = '/con/my/updateDraftFile?id=' + conId
  filemakerctrl.CallFileMaker({
    url: "/con/my/wordAutoFill/" + conId,
    success: function () {
      addOpen.value = false
      setBackdropOrDisableForDialog(false)
      proxy.$modal.alertSuccess('保存成功')
      refreshList()
    },
    error: function (msg) {
      setBackdropOrDisableForDialog(false)
      deleteCon(conId)
      proxy.$modal.alertError(msg)
    }
  })
}

/** 新建合同保存 */
function saveCon() {
  proxy.$refs["addFormRef"].validate(valid => {
    if (valid) {
      setBackdropOrDisableForDialog(true)
      addCon(proxy.addDateRange(addForm.value, 'PeriodTime')).then((conId) => {
        wordAutoFill(conId)
      }).catch(() => {
        setBackdropOrDisableForDialog(false)
      })
    }
  })
}

function refreshList() {
  activeTabName.value = '起草中'
  contractListRefs.value[1].resetQuery()
}

const clearTemplateName = () => {
  addForm.value.templateName = ''
  addForm.value.templateId = null
  addForm.value.conFile = null
}

const handleFileChange = (file) => {
  addForm.value.templateName = file.name
  addForm.value.conFile = file.raw
}

const handleExceed = (files) => {
  //清除并覆盖先前选择的文件
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}

function handleSelectedTemplate(template) {
  addForm.value.templateId = template.id
  addForm.value.conFile = null
  addForm.value.templateName = template.name
  addForm.value.tradeType = template.tradeType
  templateListOpen.value = false
}

const changHasPeriod = (val) => {
  hasPeriod.value = val
}

</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--合同数据-->
      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['con:my:add']"
            >新增
            </el-button>
          </el-col>

        </el-row>
        <el-tabs v-model="activeTabName" class="demo-tabs" @tab-change="handChangeTab" @tab-click="handClickTab">
          <el-tab-pane v-for="(status, index) in conStatus"
                       :key="status.value"
                       :name="status.value"
                       :label="status.label"
                       lazy
                       style="padding-bottom: 10px;">
            <ContractList :ref="loopSetRef(index)" :status="status.value" :conStatus="conStatus" v-if="activeTabName === status.value"/>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 添加合同对话框-->
    <el-dialog :title="addTitle" v-model="addOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-form @submit.native.prevent :model="addForm" :rules="rules" ref="addFormRef" v-loading="loading" element-loading-text="正在保存，请稍后..." label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同编号" prop="conNo">
              <el-input v-model="addForm.conNo" placeholder="请选择手动输入或自动生成合同编号" maxlength="50" clearable>
                <template #append>
                  <el-button type="success" @click="generateConNo()" style="color:#626aef;
                  border: #626aef 1px solid; border-top-left-radius: 0px; border-bottom-left-radius: 0px;">自动生成编号</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="addForm.orderNo" placeholder="订单编号" maxlength="50" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同正文" prop="templateName">
              <input type="hidden" v-model="addForm.templateId" />
              <el-input readonly :input-style="customReadonlyInputStyle" v-model="addForm.templateName" clearable @clear="clearTemplateName" placeholder="请选择合同模板 或 上传现有的 doc/docx/pdf 格式的合同" >
                <template #append>
                  <el-button type="success" @click="openTemplateDialog" class="button-spacing"
                             style="color:#626aef; border: #626aef 1px solid; ">选择合同模板</el-button>
                  &nbsp;&nbsp;&nbsp;
                  <el-upload
                      ref="uploadRef"
                      name="conFile"
                      accept=".contractInfo, .docx, .pdf"
                      action="#"
                      :limit="1"
                      :headers="upload.headers"
                      :on-change="handleFileChange"
                      :on-exceed="handleExceed"
                      :disabled="upload.isUploading"
                      :show-file-list="false"
                      :auto-upload="false"
                  >
                    <el-button slot="trigger" style="color:#626aef;border: #626aef 1px solid;">上传现有合同</el-button>
                  </el-upload>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同名称" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入合同名称" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="对方单位名称" prop="tradeCompany">
              <el-input v-model="addForm.tradeCompany" placeholder="对方单位名称" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同金额" prop="total">
              <el-input v-model="addForm.total" placeholder="合同金额最多可保留两位小数" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="买方方向" prop="tradeType">
              <el-select v-model="addForm.tradeType" placeholder="请选择">
                <el-option
                    v-for="dict in tradeType"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同类型" prop="conType">
              <el-input v-model="addForm.conType" placeholder="请输入合同类型" maxlength="100" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同期限">
              <el-switch
                  v-model="addForm.hasPeriod"
                  inline-prompt
                  active-text="有固定期限"
                  active-value="是"
                  inactive-text="无固定期限"
                  inactive-value="否"
                  style="--el-switch-on-color: #529b2e; --el-switch-off-color: #6379bb"
                  @change="changHasPeriod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16" v-show="addForm.hasPeriod==='是'">
            <el-form-item label="固定期限范围" prop="dateRange" :required="addForm.hasPeriod==='是'" style="width: 350px;">
              <el-date-picker
                  v-model="addForm.dateRange"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input v-model="addForm.memo" type="textarea" placeholder="请输入备注下信息" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <SelectTemplateList
          :is-open="templateListOpen"
          @getTemplateList="getTemplateList"
          @handleSelectedTemplate="handleSelectedTemplate"
          @close="closeTemplateDialog"
          templateType="conMyFileTemplate"/>

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="isDisabledButtons" type="primary" @click="saveCon">保 存</el-button>
          <el-button :disabled="isDisabledButtons" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<style scoped>
.button-spacing {
  margin-right: 10px;
  border: #626aef 1px solid;
}

/* 最后一个按钮不需要间隔 */
.button-spacing:last-child {
  margin-right: 0;
}
</style>
